﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using pwblog.Entities;

namespace pwblog.DataAccess
{
    public class ActiveCodeDao
    {
        ManageBlogDataContext dataContext;

        public ActiveCodeDao()
        {
            dataContext = new ManageBlogDataContext();
        }

        /// <summary>
        /// insert new active code
        /// </summary>
        /// <param name="activecode"></param>
        /// <returns></returns>
        public void InsertActiveCode(ActiveCode activeCode)
        {
            dataContext.ActiveCodes.InsertOnSubmit(activeCode);
            dataContext.SubmitChanges();
        }

        /// <summary>
        /// delete active code
        /// </summary>
        /// <param name="activecode"></param>
        /// <returns></returns>
        public void DeleteActiveCode(ActiveCode activeCode)
        {
            dataContext.ActiveCodes.DeleteOnSubmit(activeCode);
            dataContext.SubmitChanges();
        }

        /// <summary>
        /// get active code by code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActiveCode GetActiveCodeByCode(String code)
        {
            return dataContext.ActiveCodes.SingleOrDefault(item => item.Code == code);
        }

        /// <summary>
        /// get active code by username
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActiveCode[] GetActiveCodeByUsername(string username)
        {
            return dataContext.ActiveCodes.Where(item => item.Username == username).ToArray();
        }

        /// <summary>
        /// update active code
        /// </summary>
        /// <param name="newActiveCode"></param>
        /// <returns></returns>
        public void UpdateActiveCode(ActiveCode newActiveCode)
        {
            var oldActiveCode = dataContext.ActiveCodes.Single(item => item.Code == newActiveCode.Code);
            oldActiveCode.IsExpired = newActiveCode.IsExpired;
            oldActiveCode.DateCreated = newActiveCode.DateCreated;
            oldActiveCode.Username = newActiveCode.Username;

            dataContext.SubmitChanges();
        }
    }
}